package statis

import (
	"fmt"
	"strconv"
	//	"strings"

	"qkstatis/db"

	rpc "qkstatis/rpc/client/qkleague"

	"doubimeizhi.com/datatable"
	"doubimeizhi.com/utility"

	log "github.com/cihub/seelog"
)

const (
	PBL = "2fde827d756145e38b901522da979f49, 0f15fd0cfbae41b7a81f3eae63167121, e08fd35036b24f4da45a3f8f0777de91, 3b9cd5f12e2b4826b4b089cffb8a2c5f"
)

var leagueProfitStatisInstance *leagueProfitStatisService

type leagueProfitStatisService struct{}

func GetLeagueProfitStatisService() *leagueProfitStatisService {
	if leagueProfitStatisInstance == nil {
		leagueProfitStatisInstance = &leagueProfitStatisService{}
	}
	return leagueProfitStatisInstance
}

//查询列表
func (p *leagueProfitStatisService) ListLeagueProfit(sessionId string, ltype int, conditions map[string]interface{}, needTotalRecords bool) ([]*LeagueProfit, int) {
	dtq := p.leagueProfitDtq(ltype)
	//dtq.SetPage(start, length)
	for key, val := range conditions {
		dtq.PushCondition(key, val)
	}
	sql, values := dtq.GenerateSQL()
	data := make([]*LeagueProfit, 0)
	mysqlHelper := db.GetMySQLHelper()
	if results, err := mysqlHelper.Query(sql, values...); err == nil {
		if len(results) == 0 {
			log.Warnf("查询没有统计数据，conditions:%v", conditions)
			return make([]*LeagueProfit, 0, 0), 0
		}
		for _, dt := range results {
			data = append(data, p.leagueProfitParseRecords(dt, mysqlHelper, sessionId))
		}
	}
	recordsTotal := 0
	if needTotalRecords {
		s, v := dtq.GenerateTotalRecordSQL("total_records")
		if results, err := mysqlHelper.Query(s, v...); err == nil {
			if len(results) > 0 {
				recordsTotal = mysqlHelper.GetColInt(results[0], "total_records")
			}
		} else {
			log.Errorf("mysql err sql:%s, values:%v", err.Error(), v)
		}
	}
	return data, recordsTotal
}

func (p *leagueProfitStatisService) leagueProfitDtq(ltype int) *datatable.DataTableQuery {
	dtq := datatable.NewDataTableQuery()
	dtq.PushField(&datatable.FiledItem{Alias: "date_flag", Field: "date_flag", OrderBy: datatable.DESC})
	dtq.PushField(&datatable.FiledItem{Alias: "league_id", Field: "league_id"})
	dtq.PushField(&datatable.FiledItem{Alias: "washing_order", Field: "washing_order"})
	dtq.PushField(&datatable.FiledItem{Alias: "washing_profit", Field: "washing_profit"})
	dtq.PushField(&datatable.FiledItem{Alias: "washing_total", Field: "washing_total"})
	dtq.PushField(&datatable.FiledItem{Alias: "washing_discount", Field: "washing_discount"})
	dtq.PushField(&datatable.FiledItem{Alias: "washing_peer", Field: "washing_peer"})
	dtq.PushField(&datatable.FiledItem{Alias: "washer_num_active", Field: "washer_num_active"})
	dtq.PushField(&datatable.FiledItem{Alias: "washer_num_use", Field: "washer_num_use"})
	dtq.PushField(&datatable.FiledItem{Alias: "s_o1m", Field: "s_o1m"})
	dtq.PushField(&datatable.FiledItem{Alias: "s_p1m", Field: "s_p1m"})
	dtq.PushField(&datatable.FiledItem{Alias: "l_o1m", Field: "l_o1m"})
	dtq.PushField(&datatable.FiledItem{Alias: "l_p1m", Field: "l_p1m"})
	dtq.PushField(&datatable.FiledItem{Alias: "o1u", Field: "o1u"})
	dtq.PushField(&datatable.FiledItem{Alias: "u1m", Field: "u1m"})

	switch ltype {
	case 1:
		dtq.SetTableName("statis_league_profit_day")
	case 2:
		dtq.SetTableName("statis_league_profit_week")
	case 3:
		dtq.SetTableName("statis_league_profit_month")
	default:
		log.Errorf("leagueProfitDtq, 未知参数ltype； ltype:%d", ltype)
		dtq.SetTableName("none")
	}
	return dtq
}

func (p *leagueProfitStatisService) leagueProfitParseRecords(dt map[string]interface{}, mysqlHelper *utility.MySQLHelper, sessionId string) *LeagueProfit {
	lp := &LeagueProfit{}
	lp.DateFlag = mysqlHelper.GetColString(dt, "date_flag")
	if len(lp.DateFlag) == 6 {
		lp.DateFlag += GetStatisService().date2week(lp.DateFlag)
	}
	lp.LeagueId = mysqlHelper.GetColString(dt, "league_id")
	lp.WashingOrder = mysqlHelper.GetColInt(dt, "washing_order")
	lp.WashingPeer = mysqlHelper.GetColInt(dt, "washing_peer")
	lp.WasherNumActive = mysqlHelper.GetColInt(dt, "washer_num_active")
	lp.WasherNumUse = mysqlHelper.GetColInt(dt, "washer_num_use")
	lp.So1m = mysqlHelper.GetColString(dt, "s_o1m")
	lp.Lo1m = mysqlHelper.GetColString(dt, "l_o1m")
	lp.O1u = mysqlHelper.GetColString(dt, "o1u")
	lp.U1m = mysqlHelper.GetColString(dt, "u1m")

	wp := mysqlHelper.GetColInt(dt, "washing_profit")
	lp.WashingProfit = fmt.Sprintf("%.3f", float64(wp)/float64(100))
	tp := mysqlHelper.GetColInt(dt, "washing_total")
	lp.WashingTotal = fmt.Sprintf("%.3f", float64(tp)/float64(100))
	dp :=mysqlHelper.GetColInt(dt, "washing_discount")
	lp.WashingDiscount=fmt.Sprintf("%.3f",float64(dp)/float64(100))
	sp1m := mysqlHelper.GetColString(dt, "s_p1m")
	tmp, _ := strconv.ParseFloat(sp1m, 32)
	lp.Sp1m = fmt.Sprintf("%.3f", tmp/float64(100))

	lp1m := mysqlHelper.GetColString(dt, "l_p1m")
	tmp, _ = strconv.ParseFloat(lp1m, 32)
	lp.Lp1m = fmt.Sprintf("%.3f", tmp/float64(100))

	if ok, info := rpc.GetLeagueInfo(lp.LeagueId, sessionId); ok {
		if info["nick_name"].(string) == "" {
			lp.LeagueName = info["mobile"].(string)
		} else {

			lp.LeagueName = info["nick_name"].(string)
		}

		if lp.LeagueName == "" {
			log.Warnf("league-profit, league_name is empty; league_id:%s", lp.LeagueName)
		}
	}
	return lp
}
